<template>
    <div>
        <div class="ruleMessage" v-if="ruleMessage">
            {{ ruleMessage }}
        </div>
        <div class="e-table" style="background-color: #fff">
            <!-- 头部buttons -->
            <div class="top">
                <div class="left">
                    <div v-if="auditState.canModify">
                        <el-dropdown @command="selectPlan">
                            <el-button size="small" class="btn-greenYellow"
                                >选择计划<i class="el-icon-arrow-down el-icon--right"></i>
                            </el-button>
                            <el-dropdown-menu slot="dropdown">
                                <el-dropdown-item :command="1">设备采购计划</el-dropdown-item>
                            </el-dropdown-menu>
                        </el-dropdown>
                    </div>
                    <el-select
                        v-model="detailsDataCurDtlId"
                        placeholder="请选择包件"
                        style="width: 300px; margin-left: 10px"
                        @change="handleNodeClick"
                    >
                        <el-option
                            v-for="item in _detailsData"
                            :key="item.dtlId"
                            :label="item.itemNo + ' ' + item.name"
                            :value="item.dtlId"
                        >
                        </el-option>
                    </el-select>
                </div>
                <div class="right">
                    <span style="display: flex; align-items: center; margin-right: 10px">
                        <div style="width: 20px; height: 20px; background: #06ad36"></div>
                        新增
                    </span>
                    <span style="display: flex; align-items: center; margin-right: 10px">
                        <div style="width: 20px; height: 20px; background: #ff2300"></div>
                        删除
                    </span>
                    <span style="display: flex; align-items: center">
                        <div style="width: 20px; height: 20px; background: #ffa40d"></div>
                        修改
                    </span>
                </div>
            </div>
            <el-table
                :data="_tableData[dtlIndex]"
                style="width: 100%; margin-bottom: 20px"
                row-key="id"
                border
                default-expand-all
                :tree-props="{
                    children: 'children',
                    hasChildren: 'hasChildren'
                }"
                :row-class-name="tableRowClassName"
                :key="dtlIndex"
                :max-height="$store.state.tableHeight"
            ref="table"
            v-sortTable="{ tableData: tableData, _this: this, ref: 'table' }"
                @cell-mouse-enter="cellMouseEnter"
            >
                <el-table-column width="120" label="操作">
                    <template slot-scope="scope">
                        <img
                            src="@/assets/btn/delete.png"
                            alt=""
                            @click="deleteData(scope.$index)"
                            v-if="
                                auditState.canModify &&
                                scope.row.state !== -1 &&
                                scope.row.changeType !== -1 &&
                                scope.row.changeType !== -2
                            "
                            style="cursor: pointer"
                        />
                        <img
                            src="@/assets/btn/cancelDelete.png"
                            alt=""
                            @click="cancelDelete(scope.$index)"
                            v-else-if="
                                auditState.canModify &&
                                (scope.row.state === -1 ||
                                    scope.row.changeType === -1 ||
                                    scope.row.changeType === -2)
                            "
                            style="cursor: pointer"
                        />
                    </template>
                </el-table-column>
                <el-table-column type="index" label="序号" width="100"> </el-table-column>
                <el-table-column prop="name" label="设备名称" width="100"> </el-table-column>
                <el-table-column prop="unit" label="计量单位" width="100"> </el-table-column>
                <el-table-column prop="type" label="类别" min-width="200"> </el-table-column>
                <el-table-column prop="specs" label="规格型号" width="100"> </el-table-column>
                <!-- <el-table-column prop="texture" label="材质" width="100"> </el-table-column> -->
                <el-table-column prop="num" label="数量" width="100">
                    <template slot-scope="{ row }">
                        <el-input
                            v-model="row.num"
                            placeholder="请输入内容"
                            v-enterFloat2="{
                                set: row,
                                key: 'num'
                            }"
                            @input="input(row)"
                            @blur="inputblur(row, 'num')"
                            :disabled="row.changeType === -1"
                        >
                            <i
                                slot="suffix"
                                class="el-icon-tickets"
                                @click="priceHistory(row, 'numUpdateHistory')"
                                v-if="row.numUpdateHistory && row.numUpdateHistory.length !== 0"
                            ></i>
                        </el-input>
                    </template>
                </el-table-column>
                <el-table-column prop="limitPrice" label="设备申报单价（元）" width="150">
                    <template slot-scope="{ row }">
                        <el-input
                            v-model="row.limitPrice"
                            placeholder="请输入内容"
                            v-enterFloat="{
                                set: row,
                                key: 'limitPrice'
                            }"
                            @input="input(row)"
                            @blur="inputblur(row, 'limitPrice')"
                            :disabled="row.changeType === -1"
                        >
                            <i
                                slot="suffix"
                                class="el-icon-tickets"
                                @click="priceHistory(row, 'limitPriceUpdateHistory')"
                                v-if="
                                    row.limitPriceUpdateHistory &&
                                    row.limitPriceUpdateHistory.length !== 0
                                "
                            ></i>
                        </el-input>
                    </template>
                </el-table-column>
                <el-table-column prop="freightPrice" label="运输申报单价（元）" width="150">
                    <template slot-scope="{ row }">
                        <el-input
                            v-model="row.freightPrice"
                            placeholder="请输入内容"
                            v-enterFloat="{
                                set: row,
                                key: 'freightPrice'
                            }"
                            @input="input(row)"
                            @blur="inputblur(row, 'freightPrice')"
                            :disabled="row.changeType === -1"
                        >
                            <i
                                slot="suffix"
                                class="el-icon-tickets"
                                @click="priceHistory(row, 'freightPriceUpdateHistory')"
                                v-if="
                                    row.freightPriceUpdateHistory &&
                                    row.freightPriceUpdateHistory.length !== 0
                                "
                            ></i>
                        </el-input>
                    </template>
                </el-table-column>
                <el-table-column prop="unitPrice" label="综合单价（元）" width="120">
                </el-table-column>
                <el-table-column prop="amount" label="总金额（元）" width="120"> </el-table-column>
            </el-table>
        </div>
        <!-- dialog -->
        <el-dialog :visible.sync="historyDialogVisible" width="70%">
            <el-table
                :data="priceHistoryTableData"
                style="width: 100%; margin-bottom: 20px"
                row-key="id"
                border
                default-expand-all
                :max-height="$store.state.tableHeight"
            ref="table"
            v-sortTable="{ tableData: tableData, _this: this, ref: 'table' }"
            >
                <el-table-column prop="modifier" label="操作人" width="200"> </el-table-column>
                <el-table-column prop="createTime" label="核准日期" width="100"> </el-table-column>
                <el-table-column prop="originalContent" label="原数据" width="100">
                </el-table-column>
                <el-table-column prop="modifiedContent" label="核准数据" width="100">
                </el-table-column>
                <el-table-column prop="remarks" label="审核意见" width="100"> </el-table-column>
            </el-table>
            <span slot="footer" class="dialog-footer">
                <el-button @click="historyDialogVisible = false">取 消</el-button>
            </span>
        </el-dialog>
    </div>
</template>
<script>
// import ComTreeTable from '@/templates/table/treeTable.vue'
// import ComTreeFile from '@/templates/table/treeFile.vue'
// import applyRequest from '@/api/tender/apply.js'
// eslint-disable-next-line no-unused-vars
import { selectDataClient, openAppClient } from '@/utils/common'
// import { vueDom } from '@/utils/common.js'
import equipmentProcurementRequest from '@/api/tender/equipmentProcurement.js'
import { mapMutations } from 'vuex'

export default {
    props: {
        // 包件数据
        detailsData: {
            type: Array,
            default: function () {
                return []
            }
        },
        // 清单数据
        tableData: {
            type: Array,
            default: function () {
                return []
            }
        },
        // 审核按钮状态
        auditState: {
            type: Object,
            default: function () {
                return {}
            }
        }
    },
    model: {
        prop: 'tableData',
        event: 'change'
    },
    data () {
        return {
            detailsOfProposedArr: [],
            // tableData: [],
            cloneTableData: [],
            dtlId: '',
            deleteTableData: [],
            tempArr: [], //临时用来保存清单，tabledata不能直接操作
            initDataState: 0,
            MouseEnterId: 0,
            ruleMessage: '',
            historyDialogVisible: false,
            priceHistoryTableData: [],
            detailsDataCurDtlId: '',
            selectDetailState: false,
            isLoadTenderList: new Set()
        }
    },
    computed: {
        tenderId () {
            return this.$route.query.tenderId
        },
        billId () {
            return this.$route.query.billid
        },
        // 补遗里的detailsData应该是state和changeType != -1的
        _detailsData () {
            return this.detailsData.filter(item => {
                return item.state !== -1 && item.changeType !== -1
            })
        },
        // 当前选择包件的index
        dtlIndex () {
            return this._detailsData.findIndex(item => this.dtlId === item.dtlId)
        },
        // 补遗里的tableData是frontState!=-1的
        _tableData () {
            return this.tableData.filter(item => item[0]?.frontState !== -1)
        }
    },
    watch: {
        // 包件数据
        detailsData: {
            handler (newVal) {
                console.log('detailsData', newVal)
                // 处理数据获得包件列表
                this.getDetails()
                if (newVal.length === 0) {
                    this.$emit('change', [])
                    // this.tableData = []
                    this.dtlId = ''
                    this.detailsDataCurDtlId = ''
                } else {
                    // 寻找当前包件数据里是否有当前id（主要判断被删情况）
                    const findVal = newVal.find(item => item.dtlId === this.dtlId)
                    if (findVal) {
                        this.dtlId = findVal.dtlId
                    } else {
                        this.dtlId = ''
                    }
                }
                // if (newVal.length === 1) {
                //     setTimeout(() => {
                //         $('.el-tree-node:first')?.addClass('is-current')
                //     }, 100)
                // }
                // 如果包件changeType为-1，删除包件对应清单
                newVal.forEach(item => {
                    const index = this.tableData.findIndex(item2 => {
                        if (item2.length === 0) return
                        return item2[0].packageId === item.dtlId
                    })
                    if (index === -1) return
                    if (item.changeType === -1 || item.state === -1) {
                        this.$set(this.tableData[index][0], 'frontState', -1)
                    } else {
                        this.$set(this.tableData[index][0], 'frontState', 0)
                    }
                })
            },
            deep: true
        },
        // 包件id
        async dtlId (newVal) {
            this.detailsDataCurDtlId = newVal
            const tableData = JSON.parse(JSON.stringify(this.tableData))
            tableData.forEach(item => {
                if (item.length === 0) return
                delete item[0].frontState
            })
            if (
                newVal !== '' &&
                JSON.stringify(tableData[this.dtlIndex]) ===
                    JSON.stringify(this.cloneTableData[this.dtlIndex])
            ) {
                await this.getData() // 获取清单数据
                // 懒加载无法修改第2个包件（没清单数据）
                this.detailsData.forEach((item, index) => {
                    this.getData(item.dtlId, index)
                })
            }
            // 工程tableData对应的是当前table，物资、设备对应的是所有table，删除包件只应该置空对应的table，而不是所有table，上面已经将dtlId找不到就置为空，所以tableData[this.dtlIndex]是找不到的。
            // if (newVal === '') {
            //     this.tableData = []
            // }
        },
        // 监听清单
        tableData: {
            handler (newVal) {
                // 第1次启动不调用ifEdit，使用state的颜色
                this.initDataState += 1
                if (this.initDataState > 1) {
                    // 改变颜色
                    this.ifEdit(newVal, this.cloneTableData)
                }
            },
            deep: true
        }
    },
    components: {
        // ComTreeTable,
        // ComTreeFile
    },
    created () {
        // this.findByApplyId() // 获取包件列表数据
    },
    mounted () {
        // vueDom(
        //     // 默认0为选中项
        //     () => {
        //         $('.el-tree-node:first')?.addClass('is-current')
        //     },
        //     () => {
        //         return false
        //         //  $('.el-tree-node:first')?.attr('class')?.includes('is-current')
        //     }
        // )
        // setTimeout(() => {
        //     $('.el-tree-node:first')?.addClass('is-current')
        // }, 1000)
    },
    methods: {
        ...mapMutations(['setSelectedInfo']),
        // eslint-disable-next-line no-unused-vars
        cellMouseEnter (row, column, cell, event) {
            this.$bus.$emit('setDtlId', row.packageId)
        },
        priceHistory (row, arg) {
            this.historyDialogVisible = true
            this.priceHistoryTableData = row[arg]
        },
        inputblur (row, val) {
            row[val] = isNaN(parseFloat(row[val])) ? 0 : parseFloat(row[val])
        },
        tableRowClassName ({ row }) {
            // 删除显示优先级最高放前面
            if (row.state === -1 || row.changeType === -1 || row.changeType === -2) {
                return 'red'
            } else if (row.state === 1) {
                return 'green'
            } else if (row.state === 2) {
                return 'yellow'
            }
        },
        cancelDelete (index) {
            this.tableData[this.dtlIndex][index].state = 2
            this.tableData[this.dtlIndex][index].changeType = 2
        },
        deleteData (index) {
            this.tableData.forEach(() => {
                this.deleteTableData.push([])
            })
            // 新增的数据前端直接删除
            if (this.tableData[this.dtlIndex][index].state === 1) {
                this.tableData[this.dtlIndex][index].changeType = -1
                // 临时数据(changeType=1)不需要记录进删除数组
                if (this.tableData[this.dtlIndex][index].changeType !== 1) {
                    // 记录进删除数组
                    this.deleteTableData[this.dtlIndex].push(this.tableData[this.dtlIndex][index])
                }
                this.tableData[this.dtlIndex].splice(index, 1)
            } else {
                // 原数据标红
                this.tableData[this.dtlIndex][index].changeType = -2
                // 记录进删除数组
                this.deleteTableData[this.dtlIndex].push(this.tableData[this.dtlIndex][index])
            }
        },
        // 获取清单数据
        async getData (dtlId = this.dtlId, dtlIndex = this.dtlIndex) {
            if (this.isLoadTenderList.has(dtlId)) return
            // console.log('getData', this.tableData, this.dtlIndex)
            // console.log('blur', this.tableData[this.dtlIndex].find(item => item.changeType !== 0) !== undefined)
            // 如果当前包件清单有数据则不查询
            // if (this.tableData[this.dtlIndex] !== undefined) return
            // 如果当前包件清单修改过则不查询
            // if (
            //     (this.tableData[this.dtlIndex] !== undefined &&
            //         this.tableData[this.dtlIndex].find(item => item.changeType !== 0) ===
            //             undefined)
            // )
            //     return
            // console.log('this.deleteTableData', this.deleteTableData)
            // if (arg !== 0) {
            //     if (
            //         this.tableData[this.dtlIndex]?.find(item => item.changeType !== 0) !==
            //             undefined ||
            //         (this.deleteTableData[this.dtlIndex] !== undefined &&
            //             this.deleteTableData[this.dtlIndex]?.length !== 0)
            //     )
            //         return
            // }
            await equipmentProcurementRequest
                .inventoryGetByPackageId({ packageId: dtlId })
                .then(async res => {
                    // 整个清单的数据
                    if (this.tableData.length === 0) {
                        this.detailsData.forEach(() => {
                            this.tableData.push([])
                            this.cloneTableData.push([])
                        })
                    }
                    this.$set(this.tableData, dtlIndex, res)
                    this.cloneTableData[dtlIndex] = JSON.parse(JSON.stringify(res))
                    // await this.$emit('change', this.tempArr)
                    // changeType初始为0
                    this.tableData[dtlIndex].forEach(item => {
                        item.changeType = 0
                    })
                    this.cloneTableData[dtlIndex].forEach(item => {
                        item.changeType = 0
                    })
                    // console.log('getdata this.cloneTableData', this.cloneTableData)
                    // 用于判断数据是否更新
                    // this.cloneTableData = JSON.parse(JSON.stringify(this.tableData))
                    this.detailsData.forEach(item => {
                        const index = this.tableData.findIndex(item2 => {
                            if (item2.length === 0) return
                            return item2[0].packageId === item.dtlId
                        })
                        if (index === -1) return
                        if (item.changeType === -1 || item.state === -1) {
                            this.$set(this.tableData[index][0], 'frontState', -1)
                        } else {
                            this.$set(this.tableData[index][0], 'frontState', 0)
                        }
                    })
                    this.isLoadTenderList.add(dtlId)
                })
        },
        input (row) {
            // 综合单价（元） = 设备申报单价+运费申报单价
            row.unitPrice = isNaN(
                parseFloat((parseFloat(row.limitPrice) + parseFloat(row.freightPrice)).toFixed(2))
            )
                ? 0
                : parseFloat((parseFloat(row.limitPrice) + parseFloat(row.freightPrice)).toFixed(2))
            // 总金额（元）=数量*综合单价
            row.amount = isNaN(
                parseFloat((parseFloat(row.unitPrice) * parseFloat(row.num)).toFixed(2))
            )
                ? 0
                : parseFloat((parseFloat(row.unitPrice) * parseFloat(row.num)).toFixed(2))
        },
        // 如果数据修改了加上changeState1
        // 比较的是每一项，传tableData的index
        ifEdit (tableData, cloneTableData) {
            // console.log('tableData', tableData)
            // console.log('cloneTableData', cloneTableData)
            let state = false
            if (tableData === undefined && cloneTableData === undefined) return
            // const detailIndex = this.detailsData.findIndex(item => item.dtlId === this.dtlId)
            // 判断每条数据
            tableData.forEach(_item => {
                _item.forEach(item=>{
                    const itemStr =
                    JSON.stringify(item.name) +
                    JSON.stringify(item.unit) +
                    JSON.stringify(item.type) +
                    JSON.stringify(item.specs) +
                    JSON.stringify(item.num) +
                    JSON.stringify(item.limitPrice) +
                    JSON.stringify(item.freightPrice) +
                    JSON.stringify(item.unitPrice) +
                    JSON.stringify(item.amount)
                    cloneTableData.forEach(_item2 => {
                        _item2.forEach(item2=>{
                            const item2Str =
                        JSON.stringify(item2.name) +
                        JSON.stringify(item2.unit) +
                        JSON.stringify(item2.type) +
                        JSON.stringify(item2.specs) +
                        JSON.stringify(item2.num) +
                        JSON.stringify(item2.limitPrice) +
                        JSON.stringify(item2.freightPrice) +
                        JSON.stringify(item2.unitPrice) +
                        JSON.stringify(item2.amount)
                            // 判断数据是否修改
                            if (item.recordId === item2.recordId && itemStr !== item2Str) {
                                // console.log('itemStr', itemStr)
                                // console.log('item2Str', item2Str)
                                // console.log('item', item)
                                // console.log('item2', item2)
                                // 判断数量、运费单价、物资申报单价是否修改
                                if (item.num !== item2.num) {
                                    item.isUpdateNumState = true
                                } else {
                                    item.isUpdateNumState = false
                                }
                                if (item.limitPrice !== item2.limitPrice) {
                                    item.isUpdateLimitPriceState = true
                                } else {
                                    item.isUpdateLimitPriceState = false
                                }
                                if (item.freightPrice !== item2.freightPrice) {
                                    item.isUpdateFreightPriceState = true
                                } else {
                                    item.isUpdateFreightPriceState = false
                                }
                                state = true
                                // 如果不是删除状态
                                if (item.changeType !== -1 && item.changeType !== -2) {
                                    item.changeType = 2
                                    // 如果后端状态不是1
                                    if (item.state !== 1) {
                                        item.state = 2
                                    }
                                }
                            }
                        })
                    })
                })
            })
            // 边界情况：删除数据
            if (tableData.length !== cloneTableData.length) state = true
            // 边界情况：新增数据
            if (cloneTableData.length === 0) state = true
            // 边界情况：清单没数据没修改
            if (tableData.length === 0 && cloneTableData.length === 0) state = false
            return state
        },
        // 清单验证
        tenderListRule () {
            if (this.tableData.length === 0) {
                this.ruleMessage = '请添加清单'
                this.$emit('onChangeTab', { name: 'tenderListCon' })
                return false
            }
            // 清单验证
            const ruleMessageArr = []
            if (this.tableData.length === 0) {
                return true
            }
            this.tableData.forEach((item, index) => {
                index += 1
                item.forEach((item2, index2) => {
                    index2 += 1
                    if (item2.num <= 0) {
                        ruleMessageArr.push(`包件${index}清单${index2}数量必须大于0`)
                    }
                    if (item2.limitPrice <= 0) {
                        ruleMessageArr.push(`包件${index}清单${index2}物资申报单价必须大于0`)
                    }
                    if (item2.freightPrice < 0) {
                        ruleMessageArr.push(`包件${index}清单${index2}运费申报单价必须大于等于0`)
                    }
                })
            })
            this.ruleMessage = ruleMessageArr.join(',')
            if (ruleMessageArr.length === 0) {
                return true
            } else {
                this.$emit('onChangeTab', { name: 'tenderList' })
                return false
            }
        },
        // 清单保存
        save () {
            // if (!this.tenderListRule()) return Promise.reject()
            new Promise(resolve => {
                let num = 0
                let length = this.detailsData.length
                this.detailsData.forEach(async (item, index) => {
                    // 当前清单对应的包件id
                    const dtlId = item.dtlId
                    const dtlIndex = this.detailsData.findIndex(item2 => dtlId === item2.dtlId)
                    // 是否修改数据
                    // if (!this.ifEdit(this.tableData, this.cloneTableData)) {
                    //     length -= 1
                    //     return
                    // }
                    const deleteTableData =
                        this.deleteTableData[index] === undefined ? [] : this.deleteTableData[index]
                    // 列表数据会和删除数据重复，过滤相同
                    const temp = []
                    const tableData = [...this.tableData[index], ...deleteTableData].filter(
                        item => {
                            // 新增数据recordId为空不过滤
                            if (item.recordId === '') {
                                return true
                            }
                            if (temp.includes(item.recordId)) {
                                return false
                            } else {
                                temp.push(item.recordId)
                                return true
                            }
                        }
                    )
                    // 更新清单
                    await equipmentProcurementRequest.changeDtlCreate(tableData)
                    await this.getData(dtlId, dtlIndex)
                    // 更新包件
                    // equipmentProcurementRequest.packageCreate(this.detailsData)
                    num++
                    if (num === length) {
                        resolve()
                    }
                })
            }).then(() => {
                // 查询清单(不需要条件判断)
                this.initDataState = 0
                // this.getData(0)
            })
            // if (!this.ifEdit(this.tableData)) return
            // // 加上删除数据
            // const tableData = [...this.tableData, ...this.deleteTableData]
            // equipmentProcurementRequest.dtlSave(tableData)
            // 包件更新计划编号、采购最高限价
            // if (this.tableData.length !== 0) {
            //     // // 转成成后端需要的计划数据
            //     // const paln = JSON.stringify(
            //     //     Array.from(
            //     //         new Set(this.tableData.map(item => item.planDetails).filter(item => item))
            //     //     ).map(item => JSON.parse(item))
            //     // )
            //     // const priceLimit = this.tableData.reduce((prev, cur) => {
            //     //     return prev + cur.amount
            //     // }, 0)
            //     // 修改包件列表的计划编号（顺带一起保存了改变的价格数据）
            //     if (paln.length !== 0) {
            //         this.detailsData.forEach(item => {
            //             if (item.dtlId === this.dtlId) {
            //                 item.changeType = 2
            //                 item.planDetails = paln
            //                 // item.priceLimit = priceLimit
            //             }
            //         })
            //     }
            // } else {
            //     this.detailsData.forEach(item => {
            //         if (item.dtlId === this.dtlId) {
            //             item.changeType = 2
            //             item.planDetails = ''
            //             // item.priceLimit = 0
            //         }
            //     })
            // }
            // equipmentProcurementRequest.packageCreate(this.detailsData)
            // console.log('palnArr', JSON.stringify(palnArr))
            // tableData.forEach((item)=>{})
        },
        getDetails () {
            this.detailsOfProposedArr = []
            if (this.detailsData.length !== 0) {
                this.detailsData.forEach((value, index) => {
                    if (value.dtlId !== '') {
                        this.detailsOfProposedArr.push({
                            label: value.name,
                            index
                        })
                    }
                })
            }
        },
        // 选择计划
        selectPlan (PlanType2) {
            if (this.dtlId === '') {
                this.clientPop('err', '请先添加包件')
                return
            }
            // 获取已选择计划id
            const SelectedIDs =
                this.tableData[this.dtlIndex] !== undefined &&
                this.tableData[this.dtlIndex].map(item => item.equipmentlId).filter(item => item)
                    .length !== 0
                    ? this.tableData[this.dtlIndex]
                        .map(item => item.equipmentlId)
                        .filter(item => item)
                    : []
            // const InitParamsStr = {
            //     PlanType2, //计划类型
            //     BusinessType: '0', //临时需用计划业务类型（0：自购，1：租赁）
            //     PurchaseType: '0', //总计划采购类型 0：普通采购，1：集中采购
            //     IsSignContract: '0' //零星采购计划是否要签合同(0:否;1:是;)
            // }
            selectDataClient({
                SelectServiceToken: '/facilityplan/contract/plan/buy', // 客+户端对应方法名,
                IsSingleMode: false, // 是否单选 true 单选 false 多选
                SelectedIDs, // 已选中id
                InitParamsStr: JSON.stringify({
                    states: [] //单据状态 非必填
                }),
                Title: '选择计划' // 标题
            }).then(val => {
                // this.setSelectedInfo(val)
                // openAppClient('/showSelectedData', '选择结果', function () {})
                SelectedIDs
                // 假数据
                // let val = [
                //     {
                //         billId: '1525284551618392066',
                //         billNo: 'SRBCCGJH20220514003',
                //         orgId: '1439990097591140354',
                //         orgName: '四川路桥建设集团股份有限公司',
                //         planBuyDtlServices: [
                //             {
                //                 billId: '1525284551618392066',
                //                 billNo: '',
                //                 buyPlanDtlId: '1525284699845095426',
                //                 categoryId: '4',
                //                 categoryName: '推土机',
                //                 equipmentId: '1502126658530504706',
                //                 equipmentName: '设备A',
                //                 oneLevelCategoryId: '',
                //                 oneLevelCategoryName: '',
                //                 price: 100,
                //                 quantity: 10,
                //                 specificationModel: '1号机',
                //                 unit: '台'
                //             }
                //         ]
                //     },
                //     {
                //         billId: '1526807574980784129',
                //         billNo: 'SRBCCGJH20220518001',
                //         orgId: '1439990097591140354',
                //         orgName: '四川路桥建设集团股份有限公司',
                //         planBuyDtlServices: [
                //             {
                //                 billId: '1526807574980784129',
                //                 billNo: '',
                //                 buyPlanDtlId: '1526809583008018433',
                //                 categoryId: '4',
                //                 categoryName: '推土机',
                //                 equipmentId: '1523926577880690690',
                //                 equipmentName: '测试设备',
                //                 oneLevelCategoryId: '',
                //                 oneLevelCategoryName: '',
                //                 price: 1000,
                //                 quantity: 1,
                //                 specificationModel: '1#',
                //                 unit: 'm²'
                //             },
                //             {
                //                 billId: '1526807574980784129',
                //                 billNo: '',
                //                 buyPlanDtlId: '1526809583062544386',
                //                 categoryId: '7',
                //                 categoryName: '挖掘机',
                //                 equipmentId: '1517117064590585858',
                //                 equipmentName: 'dsfdsa',
                //                 oneLevelCategoryId: '',
                //                 oneLevelCategoryName: '',
                //                 price: 5000,
                //                 quantity: 1,
                //                 specificationModel: '2#',
                //                 unit: '台'
                //             },
                //             {
                //                 billId: '1526807574980784129',
                //                 billNo: '',
                //                 buyPlanDtlId: '1526809583133847553',
                //                 categoryId: '7',
                //                 categoryName: '挖掘机',
                //                 equipmentId: '1517116674784555009',
                //                 equipmentName: '123',
                //                 oneLevelCategoryId: '',
                //                 oneLevelCategoryName: '',
                //                 price: 3000,
                //                 quantity: 1,
                //                 specificationModel: '3#',
                //                 unit: '台'
                //             },
                //             {
                //                 billId: '1526807574980784129',
                //                 billNo: '',
                //                 buyPlanDtlId: '1526809583188373505',
                //                 categoryId: '6',
                //                 categoryName: '平地机',
                //                 equipmentId: '1517115054092906498',
                //                 equipmentName: '123',
                //                 oneLevelCategoryId: '',
                //                 oneLevelCategoryName: '',
                //                 price: 2000,
                //                 quantity: 1,
                //                 specificationModel: '4#',
                //                 unit: '台'
                //             },
                //             {
                //                 billId: '1526807574980784129',
                //                 billNo: '',
                //                 buyPlanDtlId: '1526809583234510850',
                //                 categoryId: '4',
                //                 categoryName: '推土机',
                //                 equipmentId: '1502126658530504706',
                //                 equipmentName: '设备A',
                //                 oneLevelCategoryId: '',
                //                 oneLevelCategoryName: '',
                //                 price: 2000,
                //                 quantity: 1,
                //                 specificationModel: '5#',
                //                 unit: '台'
                //             }
                //         ]
                //     }
                // ]
                // 过滤掉父级id
                // val = val.filter(item => item.equipmentlId)
                // 过滤基础和计划相同规格的物资
                // val.forEach((item, index) => {
                //     this.tableData[this.dtlIndex]?.forEach(item2 => {
                //         const valStr =
                //             item.equipmentlClassName + item.equipmentName + item.spec + item.unit
                //         const tableStr = item2.type + item2.name + item2.specs + item2.unit
                //         // console.log('valStr', valStr)
                //         // console.log('tableStr', tableStr)
                //         if (valStr === tableStr) {
                //             // console.log('index', index)
                //             delete val[index]
                //             // this.clientPop('err', '你已经选择了相同规格的物资')
                //         }
                //     })
                // })
                // val = val.filter(item => item !== null)
                PlanType2
                // 前端显示需要的数据格式
                const arr = []
                const valArr = [] // val里还有数据，需要转换
                val.forEach(item => {
                    valArr.push(...item.planBuyDtlServices)
                })
                valArr.forEach((item, index) => {
                    arr.push({
                        amount: 0,
                        baseLibraryId: '',
                        billId: this.tenderId,
                        changeType: 1,
                        dataType: 1,
                        freightPrice: 0,
                        isUpdateFreightPriceState: false,
                        isUpdateLimitPriceState: false,
                        isUpdateNumState: false,
                        limitPrice: 0,
                        materialId: '',
                        materialNameId: '',
                        materialTypeId: '',
                        name: '',
                        num: 0,
                        packageId: this.dtlId,
                        planDetails: '',
                        recordId: '',
                        specs: '',
                        type: '',
                        unit: '',
                        unitPrice: 0,
                        planId: '',
                        planDtlId: ''
                    })
                    arr[index].name = item.equipmentName
                    arr[index].unit = item.unit
                    // arr[index].type = item.categoryName
                    // arr[index].specs = item.specificationModel
                    arr[index].num = item.quantity
                    arr[index].materialId = item.equipmentId
                    arr[index].materialNameId = item.equipmentId
                    arr[index].materialTypeId = item.categoryId
                    arr[index].planDetails = JSON.stringify({
                        billid: item.billId,
                        billNo: item.buyPlanDtlId
                        // type: PlanType2
                    })
                    arr[index].planId = item.billId
                    arr[index].planDtlId = item.buyPlanDtlId
                })
                // val.forEach((item, index) => {})
                // console.log(' this.tableData', this.tableData, this.tableData[this.dtlIndex])
                this.tableData[this.dtlIndex].push(...arr)
                console.log('request', this.tableData, this.dtlIndex)
            })
        },
        // 选择基础库
        selectBaseLibrary () {
            if (this.dtlId === '') {
                this.clientPop('err', '请先添加包件')
                return
            }
            // 获取已选择基础id
            const SelectedIDs =
                this.tableData[this.dtlIndex].map(item => item.baseLibraryId).filter(item => item)
                    .length !== 0
                    ? this.tableData[this.dtlIndex]
                        .map(item => item.baseLibraryId)
                        .filter(item => item)
                    : []
            const InitParamsStr = {
                categoryId: '00000',
                isUpdate: false,
                keyword: ''
            }
            // console.log('SelectedIDs', SelectedIDs)
            selectDataClient({
                SelectServiceToken: '/facilitybase/equipment/getEquipmentCategoryAll', // 客户端对应方法名
                IsSingleMode: false, // 是否单选 true 单选 false 多选
                SelectedIDs, // 已选中id
                InitParamsStr: JSON.stringify(InitParamsStr),
                Title: '选择基础库' // 标题
            }).then(val => {
                // this.setSelectedInfo(val)
                // openAppClient('/showSelectedData', '选择结果', function () {})
                // 假数据
                // let val = [
                //     {
                //         billId: '1492034624291868674',
                //         classIdPath: '1492338036615155713/1492338402287161345/1492339386505760770',
                //         className: '一级钢材',
                //         classNamePath: '主要材料/建筑钢材/一级钢材',
                //         equipmentName: '钢材0004',
                //         spec: '规格4',
                //         unit: 'T'
                //     },
                //     {
                //         billId: '1492034594352926722',
                //         classIdPath: '1492338036615155713/1492338402287161345/1492339386505760770',
                //         className: '一级钢材',
                //         classNamePath: '主要材料/建筑钢材/一级钢材',
                //         equipmentName: '钢材0003',
                //         spec: '规格3',
                //         unit: 'T'
                //     }
                // ]
                // 过滤基础和计划相同规格的物资
                val.forEach((item, index) => {
                    this.tableData[this.dtlIndex].forEach(item2 => {
                        const valStr =
                            item.classNamePath + item.equipmentName + item.spec + item.unit
                        const tableStr = item2.type + item2.name + item2.specs + item2.unit
                        if (valStr === tableStr) {
                            // console.log('index', index)
                            delete val[index]
                            // this.clientPop('err', '你已经选择了相同规格的物资')
                        }
                    })
                })
                val = val.filter(item => item !== null)
                // this.setSelectedInfo(val)
                // openAppClient('/showSelectedData', '选择结果', function () {})
                const arr = []
                val.forEach((item, index) => {
                    arr.push({
                        amount: 0,
                        billId: this.tenderId,
                        changeType: 1,
                        freightPrice: 0,
                        limitPrice: 0,
                        name: '',
                        num: 0,
                        packageId: this.dtlId,
                        recordId: '',
                        specs: '',
                        texture: '',
                        type: '',
                        unit: '',
                        unitPrice: 0,
                        dataType: 2,
                        baseLibraryId: ''
                    })
                    arr[index].name = item.equipmentName
                    arr[index].specs = item.spec
                    arr[index].unit = item.unit
                    arr[index].type = item.classNamePath
                    arr[index].baseLibraryId = item.billId
                    arr[index].planDetails = JSON.stringify({
                        billid: item.billId,
                        billNo: item.billNo
                    })
                })
                // console.log('this.dtlIndex', this.dtlIndex)
                this.tableData[this.dtlIndex].push(...arr)
                console.log('this.tableData', this.tableData)
            })
        },
        handleNodeClick (dtlId) {
            this.$bus.$emit('setDtlId', dtlId)
            const item = this.detailsData.find(item2 => item2.dtlId === dtlId)
            this.selectDetailState = true
            // 获取清单数据
            this.dtlId = item.dtlId
            // console.log('data', data)
            // console.log('node', node)
            // console.log('el', el)
        },
        // async findByApplyId () {
        //     let data = []
        //     let leftTree = []
        //     if (this.detailsOfProposed.length !== 0) {
        //         data = this.detailsOfProposed
        //     } else {
        //         await applyRequest.bidPackageListByBillId(this.tenderId).then(res => {
        //             data = res
        //             // this.detailsOfProposedArr = res
        //             // this.tableData.forEach(value => {
        //             //     // table显示需要的字段
        //             //     value.subcontractorName =
        //             //         (value.subcontractor[0] && value.subcontractor[0].subcontractorId) || ''
        //             // })
        //             // this.pagination.total = res.totalCount || res.length
        //         })
        //     }
        //     data.forEach(value => {
        //         leftTree.push({ label: value.name })
        //     })
        //     this.detailsOfProposedArr = leftTree
        // },
        openNewPage (name) {
            this.$notify.closeAll()
            if (name === 'tenderList') {
                const params = JSON.stringify({
                    // 正式环境应该不用转换
                    title: '选择清单',
                    url: '',
                    method: 'get',
                    params: { tenderId: this.tenderId }, // 基础id获取包件
                    tableColumnAttr: this.orgSelectTableColumnAttr,
                    tableColumnWidth: this.selectTableColumnWidth,
                    ifPagination: 0
                })
                this.$notify({
                    title: '选择清单',
                    dangerouslyUseHTMLString: true,
                    message: `正式环境：客户端打开新页面<br>
                测试环境：手动打开新页面<br>
                <textarea cols="35" rows="10">http://localhost:8080/selectData?params=${params}</textarea>
                <br><br>
                回调参数：<br>
                <textarea cols="35" rows="3" id="callBackData"></textarea><br>
                <button id="getPopData">执行回调方法</button>
                `,
                    duration: 0
                })
                document.querySelector('#getPopData').addEventListener('click', this.orgGetPopData)
            }
        }
    }
}
</script>
<style lang="scss" scoped>
.ruleMessage {
    margin-bottom: 10px;
    margin-left: 10px;
    color: red;
}

.e-table {
    background: #fff;
}

.el-table--enable-row-hover ::v-deep.el-table__body tr:hover > td {
    background-color: transparent;
}
</style>
